package handlers

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type AuthHandler struct {
	config map[string]interface{}
}

type UserContext struct {
	Username    string   `json:"username"`
	Containers  []string `json:"containers"`
	Permissions []string `json:"permissions"`
	Description string   `json:"description"`
}

func NewAuthHandler(config map[string]interface{}) *AuthHandler {
	return &AuthHandler{
		config: config,
	}
}

func (h *AuthHandler) LoginPage(c *gin.Context) {
	swiftConfig := h.config["swift"].(map[string]interface{})

	c.HTML(http.StatusOK, "login.html", gin.H{
		"username":  swiftConfig["username"],
		"password":  swiftConfig["password"],
		"auth_mode": swiftConfig["auth_mode"],
	})
}

func (h *AuthHandler) Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.HTML(http.StatusBadRequest, "login.html", gin.H{
			"error":     "用户名和密码不能为空",
			"demo_user": h.getDemoUser(),
		})
		return
	}

	// 验证用户凭证
	userContext, err := h.validateUser(username, password)
	if err != nil {
		c.HTML(http.StatusUnauthorized, "login.html", gin.H{
			"error":     "用户名或密码错误",
			"demo_user": h.getDemoUser(),
		})
		return
	}

	// 保存用户会话
	h.saveUserSession(c, userContext)

	// 重定向到主页面
	c.Redirect(http.StatusFound, "/webdrive")
}

func (h *AuthHandler) Logout(c *gin.Context) {
	// 清除会话cookies
	c.SetCookie("user_session", "", -1, "/", "", false, true)
	c.SetCookie("username", "", -1, "/", "", false, false)
	c.SetCookie("user_containers", "", -1, "/", "", false, false)
	c.SetCookie("user_permissions", "", -1, "/", "", false, false)

	c.Redirect(http.StatusFound, "/")
}

func (h *AuthHandler) RequireAuth(c *gin.Context) {
	username, err := c.Cookie("username")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}

	containersStr, err := c.Cookie("user_containers")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}

	permissionsStr, err := c.Cookie("user_permissions")
	if err != nil {
		c.Redirect(http.StatusFound, "/")
		c.Abort()
		return
	}

	// 解析容器和权限列表
	containers := strings.Split(containersStr, ",")
	permissions := strings.Split(permissionsStr, ",")

	userContext := &UserContext{
		Username:    username,
		Containers:  containers,
		Permissions: permissions,
	}

	c.Set("user", userContext)
	c.Next()
}

func (h *AuthHandler) RequirePermission(permission string) gin.HandlerFunc {
	return func(c *gin.Context) {
		user, exists := c.Get("user")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
			c.Abort()
			return
		}

		userContext := user.(*UserContext)

		hasPermission := false
		for _, perm := range userContext.Permissions {
			if perm == permission {
				hasPermission = true
				break
			}
		}

		if !hasPermission {
			c.JSON(http.StatusForbidden, gin.H{"error": "权限不足"})
			c.Abort()
			return
		}

		c.Next()
	}
}

func (h *AuthHandler) validateUser(username, password string) (*UserContext, error) {
	swiftConfig := h.config["swift"].(map[string]interface{})

	// 简化验证：只检查是否与配置中的Swift用户匹配
	if swiftConfig["username"].(string) == username {
		// 为Swift用户创建完整权限上下文
		return &UserContext{
			Username:    username,
			Containers:  []string{swiftConfig["container_name"].(string)},
			Permissions: []string{"read", "write", "delete"},
			Description: "Swift对象存储用户",
		}, nil
	}

	return nil, fmt.Errorf("用户不存在或密码错误")
}

func (h *AuthHandler) saveUserSession(c *gin.Context, userContext *UserContext) {
	c.SetCookie("user_session", "active", 3600*4, "/", "", false, true)
	c.SetCookie("username", userContext.Username, 3600*4, "/", "", false, false)
	c.SetCookie("user_containers", strings.Join(userContext.Containers, ","), 3600*4, "/", "", false, false)
	c.SetCookie("user_permissions", strings.Join(userContext.Permissions, ","), 3600*4, "/", "", false, false)
}

func (h *AuthHandler) getDemoUser() map[string]interface{} {
	swiftConfig := h.config["swift"].(map[string]interface{})

	return map[string]interface{}{
		"username":  swiftConfig["username"],
		"auth_mode": swiftConfig["auth_mode"],
		"container": swiftConfig["container_name"],
	}
}
